package com.jinglu.cloud.security.point;

import com.jinglu.cloud.common.model.entity.Result;
import com.jinglu.cloud.security.model.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author lvzhenzhao
 * @Datetime 2021/03/02-下午3:22
 */
@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException exception) throws IOException, ServletException {
        log.info("JwtAuthenticationEntryPoint:{}", exception.getMessage());
        httpServletResponse.setContentType("application/json;charset=utf-8");
        Result<String> result;
        if(exception instanceof AuthenticationCredentialsNotFoundException){
            result = Result.error(ErrorCode.UNAUTHORIZED, exception.getMessage());
        }else{
            result = Result.error(ErrorCode.UNAUTHORIZED,"未登录/没有权限.");
        }
        httpServletResponse.getOutputStream().write(result.toString().getBytes("UTF-8"));
        httpServletResponse.flushBuffer();
    }
}
